package com.example.nio.utils;

import com.example.nio.commons.Agent;
import com.example.nio.commons.Message;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

public class AssignedUtil {

    private static final Logger logger = LoggerFactory.getLogger(AssignedUtil.class);
    /**
     * String department组名 List<Agent> 客服对象集合
     */
    public static Map<String, List<Agent>> assigned = new Hashtable<>();

    private static int list = 0;

    public static void setList(int list) {
        AssignedUtil.list = list;
    }

    // 判断appid是否存在
    public static boolean checkGroup(String department) {
        if (assigned.containsKey(department) && assigned.get(department).size() != 0) {
            return true;
        }
        return false;
    }

    // 根据ip设置通道 已经存在返回ture，反则false
    public static boolean dochannel(Channel channel) {
        boolean flag = false;
        for (String assigneds : assigned.keySet()) {
            for (Agent ag : assigned.get(assigneds)) {
                InetSocketAddress insocket = (InetSocketAddress) ag.getChannel().remoteAddress();
                String ip = insocket.getAddress().getHostAddress();
                InetSocketAddress insocket2 = (InetSocketAddress) channel.remoteAddress();
                String ip2 = insocket2.getAddress().getHostAddress();
                logger.info(insocket2.getAddress().getHostAddress() + insocket2.getAddress().getHostName());
                if (ip2.equals(ip)) {
                    ag.setChannel(channel);
                    Message message = new Message();
                    List<String> toUserList = AgentUserUtil.getUserByAgent(ag);
                    for (int i = 0; i < toUserList.size(); i++) {
                        message.setTo(toUserList.get(i));
                        message.setContent("非常抱歉，由于业务繁忙导致连接异常，后续咨询请重新输入0，感谢您的支持与信任！");
                        message.setFrom(ag.getDepartment());
                        // 客服发送消息给用户
                    }
                    AgentUserUtil.deleteAgent(ag);
                    flag = true;
                }
            }
        }
        return flag;

    }

    // 根据客服id检索组名
    public static String getGroupByAgentId(String agentId) {
        String aim = null;
        for (String assigneds : assigned.keySet()) {
            for (Agent ag : assigned.get(assigneds)) {
                if (ag.getAgent().equals(agentId)) {
                    aim = assigneds;
                }
            }
        }
        return aim;
    }

    // 根据客服id得到AGENT
    public static Agent getAgentByAgentId(String agentId) {
        Agent aim = null;
        for (String assigneds : assigned.keySet()) {
            for (Agent ag : assigned.get(assigneds)) {
                if (ag.getAgent().equals(agentId)) {
                    aim = ag;
                }
            }
        }
        return aim;
    }

    // 根据组获取客服集合
    public static List<Agent> getAgentByDepartment(String department) {
        return assigned.get(department);
    }

    // 根据channel名获得agent
    public static Agent getAgentByChannel(Channel channel) {
        Agent agent = null;
        for (String assigneds : assigned.keySet()) {
            for (Agent ag : assigned.get(assigneds)) {
                if (ag.getChannel().equals(channel)) {
                    agent = ag;
                }
            }
        }
        return agent;
    }

    // 添加新组
    public static void addGroupAgent(String department) {
        logger.info("添加组:"+department);
        assigned.put(department, new ArrayList<Agent>());
    }

    // 删除组
    public static void deleteGroupAgent(Agent agent) {
        logger.info("删除组:"+agent.getDepartment());
        assigned.remove(agent.getDepartment());
    }

    // 添加新客服
    public static void addAgent(Agent agent) {
        if (!assigned.containsKey(agent.getDepartment())) {
            addGroupAgent(agent.getDepartment());
        }
        assigned.get(agent.getDepartment()).add(agent);
    }


    // 客服断开连接
    public static void deleteAgent(Agent agent) {
        if(assigned.get(agent.getDepartment()).size() != 0){
            List<Agent> agentList = assigned.get(agent.getDepartment());
            for(int i = 0;i < agentList.size();i ++){
                if(agentList.get(i).getAgent().equals(agent.getAgent())){
                    agentList.remove(i);
                }
            }
        }
    }

    // 分配客服
    public static Agent distribution(String department) {
        Agent agent = null;
        if(assigned.get(department).size() == 0){
            return null;
        }
        for(Agent agents : assigned.get(department)){
            if(agents.getCheckUser() < list && agents.getState() == 1){
                if(agent == null || agent.getCheckUser() > agents.getCheckUser()){
                    agent = agents;
                }
            }
        }
        if(agent != null){
            for(Agent agents : assigned.get(department)){
                if(agents.getAgent().equals(agent.getAgent())){
                    agents.setCheckUser(agents.getCheckUser() + 1);
                }
            }
        }
        return agent;
    }

    // 客服与用户断开连接  正在聊天的连接数-1
    public static void disconnect(String deleteUser) {
        Agent agent = AgentUserUtil.getAgentByUser(deleteUser);
        List<Agent> agentList = new ArrayList<Agent>();
        for (String assigneds : assigned.keySet()) {
            agentList = assigned.get(assigneds);
        }
        for (int i = 0; i < agentList.size(); i++) {
            if (agentList.get(i).getAgent().equals(agent.getAgent())) {
                agentList.get(i).setCheckUser(agentList.get(i).getCheckUser() - 1);
            }
        }
    }

    // 用户与客服建立连接
    public static void link(Agent agent) {
        for (String assigneds : assigned.keySet()) {
            List<Agent> agentList = assigned.get(assigneds);
            for (Agent value : agentList) {
                if (value.equals(agent)) {
                    value.setCheckUser(value.getCheckUser() + 1);
                }
            }
        }
    }

    //用户排队超时  消息群发客服

    //转移客服
    public static void recording(String department,String oldAgent,String newAgent){
        List<Agent> agentList = assigned.get(department);
        if(agentList.size() != 0){
            agentList.forEach(item -> {
                if(item.getAgent().equals(oldAgent)){
                    item.setCheckUser(item.getCheckUser() - 1);
                }
                if(item.getAgent().equals(newAgent)){
                    item.setCheckUser(item.getCheckUser() + 1);
                }
            });
        }
    }
    // 重置agent里面的channel
    public static void resetAgent(Agent agent){
        if(assigned.get(agent.getDepartment()).size() != 0){
            List<Agent> agentList = assigned.get(agent.getDepartment());
            for(int i = 0;i < agentList.size();i ++){
                if(agentList.get(i).getAgent().equals(agent.getAgent())){
                    agentList.get(i).setChannel(agent.getChannel());
                }
            }
        }

    }
}
